// pages/home/home.js
var Zan = require('../../dist/index');
var bananer = require('../../template/HomeTemp.js');
let network = null;
let utils = null;
let api = null;
// 获取应用实例
let app = getApp()
let count = 0;
let constants = null;
let WxNotificationCenter = require('../../utils/WxNotificationCenter.js');
let start = 0;

/**
 * 所有商品 0 (旧数据) 
 * 商品详情 1 
 * 商品分类 2 
 * 优惠券列表 3 
 * 商品搜索 4 
 * 到店自提 5 (旧数据) 
 * 拼团详情 6
 * 文章详情 7 
 * 文章分类 8 
 * 拼团列表 9
 * 积分商品列表 10 
 * 积分商品详情 11 
 * 分销页面 12 
 * 门店列表 13 
 * 门店详情 14
 */
Page(Object.assign({}, Zan.Tab, Zan.TopTips, {

  /**
   * 页面的初始数据
   */
  data: {
    frame: [],
    bananer: {},
    city: null,
    district: null,
    circle: null,
    longitude: 0,
    latitude: 0,
    bananerItem: [],
    navigateItem: [],
    recommendBrand: [],
    tab: {
      list: [{
        id: 1,
        title: '附近'
      }, {
        id: 2,
        title: '最新'
      }, {
        id: 3,
        title: '最热'
      }],
      selectedId: 1,
      height: 45,
      scroll: false
    },
    couponList01: [],
    couponList02: [],
    couponList03: [],
    activeIndex: 1,
    recordsTotal: 0,
    imgSize: 0,
    nodata: {
      msg: '暂无数据',
      notype: 1,
      imgurl: '/images/nodatas.png',
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();
    constants = new app.Constants();

    // 注册列表刷新事件
    WxNotificationCenter.addNotification("RefreshHome", this.refreshNotification, this)

    this.getLocation();

    this.setData({
      utils: utils,
      imgSize: utils.windowSize().winWidth / 3 - 30,
      height: utils.windowSize().winWidth / 750 * 400,
      bananer: {
        autoplay: true,
        interval: 5000,
        duration: 300,
        indicatorDots: true,
        circular: true,
        height: utils.windowSize().winWidth / 750 * 220
      },
    })
    
    // wx.downloadFile({
    //   url: 'http://img.1miaodao.cn/brand588.png', //仅为示例，并非真实的资源
    //   // data:{
    //   //   storeId:'bdPUxNG3QRN9qh5SBFaQHS'
    //   // },
    //   success: function (res) {
    //     // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
    //     console.log('+++++++++++++++++++++++++++++++++++++++++++++++++++++++')
    //     console.log(res)
    //     if (res.statusCode === 200) {
    //       wx.saveImageToPhotosAlbum({
    //         success(res) {
    //           filePath: res.tempFilePath
    //         }
    //       })
    //     }
    //   }
    // })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    app.globalData.timeStamp = app.globalData.timeStamp + 500;

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    WxNotificationCenter.removeNotification("RefreshHome", this);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
    console.log(this.data.activeIndex);
    if (this.data.activeIndex == 1) {
      this.setData({
        couponList01: []
      })
    } else if (this.data.activeIndex == 2) {
      this.setData({
        couponList02: []
      })
    } else {
      this.setData({
        couponList03: []
      })
    }

    // 优惠券列表
    network._post_page_json(this, api.couponHome, 0, { lng: this.data.longitude, lat: this.data.latitude, types: this.data.activeIndex, city: this.data.city, district: this.data.district, businessAreaId: this.data.circleId }, couponSuccess);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // if (this.data.items.length < this.data.recordsTotal) {
    //   start = start + 20;
    //   // 优惠券列表
    //   network._post_page_json(that, api.couponHome, start, { lng: longitude, lat: latitude, types: this.data.activeIndex + 1, city: location.city, district: location.district, businessAreaId: obj.id }, couponSuccess);
    // }
  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },

  getLocation: function () {
    const that = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        let latitude = res.latitude
        let longitude = res.longitude
        wx.request({
          url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${constants.key}`,
          success: res => {
            let location = res.data.result.ad_info;
            that.setData({
              city: location.city,
              district: location.district,
              latitude: latitude,
              longitude: longitude
            })
            // 获取Banner
            network._post_request(that, api.getBannerList, 0, 8, { city: location.city, district: location.district }, bannerSuccess);
            // 获取分类
            network._post_request(that, api.getChildTenantType, 0, 8, { city: location.city, district: location.district }, typeSuccess);
            // 获取推荐品牌
            network._post_request(that, api.getBrandList, 0, 9, { city: location.city, district: location.district }, brandSuccess);
            // // 优惠券列表
            network._post_page_json(that, api.couponHome, 0, { lng: longitude, lat: latitude, types: 1, city: location.city, district: location.district }, couponSuccess);
          },
          fail: res => {
            console.log('++++++++++++++')
            console.log(res)
          }
        })
      }
    })
  },


  handleZanTabChange(e) {
    
    var componentId = e.componentId;
    var selectedId = e.selectedId;

    this.setData({
      [`${componentId}.selectedId`]: selectedId
    });

    this.setData({
      activeIndex: selectedId,
      couponList01: [],
      couponList02: [],
      couponList03: []
    })

    // 优惠券列表
    network._post_page_json(this, api.couponHome, 0, { lng: this.data.longitude, lat: this.data.latitude, types: this.data.activeIndex, city: this.data.city, district: this.data.district, businessAreaId: this.data.circleId }, couponSuccess);
  },

  onBananerItemClick: function (e) {
    let item = e.currentTarget.dataset.item;
    let imgUrls = item.listBannerDtl;
    if (utils.canTap(e)) {
      wx.navigateTo({
        url: '/pages/home/BananerDetails?imgUrls=' + JSON.stringify(imgUrls),
      })
    }
  },

  onNavigateItemClick: function (e) {
    let id = e.currentTarget.dataset.id;
    let name = e.currentTarget.dataset.name;
    if (utils.canTap(e)) {
      wx.navigateTo({
        url: '/pages/discount/ClassCoupon' + '?id=' + id + '&name=' + name,
      })
    }
  },

  onRecommendItemClick: function (e) {
    let id = e.currentTarget.dataset.id;
    let name = e.currentTarget.dataset.name;
    if (utils.canTap(e)) {
      wx.navigateTo({
        url: '/pages/discount/BrandCoupon' + '?brandId=' + id + '&name=' + encodeURIComponent(name) + '&status=' + 1,
      })
    }
  },

  goLocationCircle: function (e) {
    wx.navigateTo({
      url: '/pages/home/LocationCircle'
    })
  },

  goCouponSearch: function (e) {
    wx.navigateTo({
      url: '/pages/discount/SearchCoupon'
    })
  },

  goCouponDetails: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/discount/CouponDetails' + '?couponId=' + id,
    })
  },

  /**
   * 刷新地址
   */
  refreshNotification: function (obj) {
    console.log(obj)
    this.setData({
      city: obj.city,
      district: obj.district,
      circleName: obj.name,
      circleId: obj.id,
    })

    // 获取Banner
    network._post_request(this, api.getBannerList, 0, 8, { city: this.data.city, district: this.data.district, businessAreaId: obj.id }, bannerSuccess);
    // 获取分类
    network._post_request(this, api.getChildTenantType, 0, 8, { city: this.data.city, district: this.data.district, businessAreaId: obj.id }, typeSuccess);
    // 获取推荐品牌
    network._post_request(this, api.getBrandList, 0, 9, { city: this.data.city, district: this.data.distric, businessAreaId: obj.id }, brandSuccess);
    // 优惠券列表
    network._post_page_json(this, api.couponHome, 0, { lng: this.data.longitude, lat: this.data.latitude, types: this.data.activeIndex, city: this.data.city, district: this.data.district, businessAreaId: obj.id }, couponSuccess);
  }
}))

var bannerSuccess = function (that, res) {
  if (res.data.data) {
    that.setData({
      bananerItem: res.data.data
    })
  }
}

var typeSuccess = function (that, res) {
  if (res.data.data) {
    that.setData({
      navigateItem: res.data.data
    })
  }
}

var brandSuccess = function (that, res) {
  if (res.data.data) {
    that.setData({
      recommendBrand: res.data.data
    })
  }
}

var couponSuccess = function (that, res) {
  if (res.data.data) {
    if (that.data.activeIndex == 1) {
      that.setData({
        couponList01: that.data.couponList01.concat(res.data.data),
        recordsTotal: res.data.recordsTotal
      })
    } else if (that.data.activeIndex == 2) {
      that.setData({
        couponList02: that.data.couponList02.concat(res.data.data),
        recordsTotal: res.data.recordsTotal
      })
    } else if (that.data.activeIndex == 3) {
      that.setData({
        couponList03: that.data.couponList03.concat(res.data.data),
        recordsTotal: res.data.recordsTotal
      })
    }
  }
}